package com.chenjw.flow;

import java.util.Date;

import com.chenjw.flow.dao.Flow;
import com.chenjw.flow.dao.Flow.FlowColumns;

import android.app.Service;
import android.content.ContentValues;
import android.content.Intent;
import android.database.sqlite.SQLiteDatabase;
import android.net.TrafficStats;
import android.net.Uri;
import android.os.Handler;
import android.os.IBinder;
import android.os.Looper;
import android.os.Message;
import android.os.SystemClock;

public class FlowInfoCollecterService extends Service {

    // private long n = 0;
    private Thread  t;
    private boolean isRunning = true;
    private long    interval  = 3600000L;

    @Override
    public IBinder onBind(Intent intent) {

        return null;
    }

    private void doSend(Long obj) {
        Intent i = new Intent();
        i.setAction("FlowInfoCollecterService.send");
        i.putExtra("msg", obj);
        // this.sendBroadcast(i);
        ContentValues values = new ContentValues();
        values.put(FlowColumns.FLOW, obj);
        values.put(FlowColumns.CREATE_DATE, new Date().getTime());
        this.getContentResolver().insert(Flow.CONTENT_URI, values);
        // flowSqlHelper.insertFlowInfo(db, new Date(), num);
    }

    @Override
    public void onDestroy() {
        this.isRunning = false;
        super.onDestroy();
    }

    @Override
    public void onCreate() {
        System.out.println("onCreate");
        super.onCreate();
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        // System.out.println(1);
        // doSend(++n);
        // return super.onStartCommand(intent, flags, startId);
        t = new Thread() {

            @Override
            public void run() {
                Looper looper = Looper.getMainLooper();
                Handler handler = new Handler(looper) {

                    @Override
                    public void handleMessage(Message msg) {
                        Long num = (Long) msg.obj;
                        doSend(num);
                    }

                };
                // long n = 0;
                while (true) {
                    if (!isRunning) {
                        break;
                    }
                    Long l = TrafficStats.getMobileTxBytes();
                    Message m = handler.obtainMessage(1, 1, 1, l);
                    handler.sendMessage(m);
                    // n++;

                    System.out.println(this.getName() + " running!");
                    SystemClock.sleep(interval);
                }
                System.out.println(this.getName() + "finished!");
            }

        };
        t.start();
        return super.onStartCommand(intent, flags, startId);
    }

}
